
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>

#include <swarm.h>
#include <swarmio.h>
#include <sw_signal.h>

void sw_signal_die(int signum){

  fprintf(stderr, "[swarm] Program crash detected in signal handler.\n");
  fprintf(stderr, "[swarm]   There is a bug some where.\n");
  sw_exit(1);

}

void sw_flush_io(){

  fflush(stdout);
  fflush(stderr);

}

/**
 * Handle a segmentation fault. Print some diagnostic info and then
 * exit.
 */
void sw_signal_sigsegv(int sig_num){

  signal(SIGSEGV, sw_signal_die);

  fprintf(stderr, "[swarm] SIGSEGV caught. Swarm crash info:\n");
  // Print the swarm data.
  sw_print_swarm_info(internal_sw);

}

void sw_signal_io_sigsegv(int sig_num){

  signal(SIGSEGV, sw_signal_die);

  sw_flush_io();

  // Print the symbol table.
  fprintf(stderr, "[swarm] SIGSEGV caught. I/O parsing info:\n");
  sw_print_swarm_info(internal_sw);
  sw_print_force_table(internal_sw);
  _swio_print_sym_table();
  sw_exit(1);

}

/**
 * Set all the dsignal handlers that we want changed.
 */
void sw_init_signals(){

  signal(SIGSEGV, sw_signal_sigsegv);

} 

void sw_signal(int sig, sighandler_t handler){

  signal(sig, handler);

}
